/* eslint-disable new-cap */
import CRUD from '../src/index';
import axios from 'axios';
import {each} from '@holyhigh/func.js/collection';

// ////////////////////模拟部分，这部分内容在适配器中自动处理
const $crud = new CRUD('/api/users');
$crud.vm = {};
CRUD.request = axios;
// ///////////////////

// 初始化数据
window.onload = function() {
  $crud.reload();
};
window.add = function() {
  // ////////////////////模拟部分，这部分内容在适配器中自动处理
  $crud.formStatus = 1;
  // ///////////////////
  $crud.submit();
};
window.del = function(id) {
  $crud.toDelete({id: id});
};
window.query = function() {
  $crud.query.keyword = document.getElementById('keyword').value;
  $crud.toQuery();
};
window.goto = function(page) {
  $crud.pagination.currentPage = page;
  $crud.toQuery();
};
window.reset = function() {
  $crud.query.keyword = document.getElementById('keyword').value = '';
  $crud.toQuery();
};

$crud.view.queryShow = false;
CRUD.defaults.view.queryShow = true;
const x = $crud.view.queryShow;
console.log(x);
CRUD.defaults.pagination.pageSize = 10;
// 全局钩子
CRUD.defaults[CRUD.HOOK.AFTER_QUERY] = function(crud, rs) {
  console.log('数据加载完成', rs);
  let listHTML = '';
  each(rs.data.rows, (row)=>{
    listHTML += `<tr>
    <td>${row.uname}</td>
    <td>${row.email}</td>
    <td>${row.ip}</td>
    <td>${row.domain}</td>
    <td>
      <a href="javascript:del('${row.id}')">删除</a>
    </td>
    </tr>`;
  });

  let pageLinks = '';

  const pages = Math.ceil(rs.data.total/15);
  for (let i=1; i<=pages; i++) {
    pageLinks += `<button onclick="goto(${i})">${i}</button>`;
  }

  document.getElementById('footer').innerHTML = pageLinks;
  document.getElementById('table').innerHTML = listHTML;
  document.getElementById('total').innerText = rs.data.total;
};
CRUD.defaults[CRUD.HOOK.AFTER_SUBMIT] = function() {
  console.log('新增成功');
  $crud.toQuery();
};
CRUD.defaults[CRUD.HOOK.AFTER_DELETE] = function() {
  console.log('删除成功');
};
CRUD.defaults[CRUD.HOOK.ON_ERROR] = function(crud, e) {
  console.error(e);
};
